package com.yilin.tms.capital.service.impl;

import com.google.gson.reflect.TypeToken;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.JsonUtil;
import com.yilin.commons.util.MapUtil;
import com.yilin.tms.capital.commons.pab.PabTradeRecord;
import com.yilin.tms.capital.service.IPsbService;
import com.yilin.tms.core.application.PlatRequest;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.capital.BankCard;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
/**
 * 邮政银行
 * */
@Service
public class PsbService implements IPsbService {
    @Resource
    private  TradeRecordService tradeRecordService;
    @Resource
    private IUserRemote userRemote;
    /**
     * 邮政银行付款
     * */
    @Override
    public void paymentTransfe(List<TradeRecord> tradeRecordList, Account loginUser) {
        boolean hasDifferentIds = tradeRecordList.stream().map(TradeRecord::getPaymentOrganizeId).distinct().count() > 1;
        if (hasDifferentIds) throw new BusinessException("存在付款人不一致，禁止批量付款！");
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(ArrayUtil.first(tradeRecordList).getPlatId()));
        ParamUtil.isNull(platProduct, "获取平台配置信息失败");
        Map<String, Object> map = new HashMap<>();
        if (tradeRecordList.size() == 1) {//单条
            TradeRecord tradeRecord = ArrayUtil.first(tradeRecordList);
            tradeRecord.setInitiateTime(new Date());
            putTradeRecordMapParam(map, tradeRecord);
            String reqUrl = platProduct.getNetworkFreightUrl() + "/platform/psb/paymentTransfer";
            PabTradeRecord pabTrade = PlatRequest.request(loginUser.getToken(), reqUrl, map, new TypeToken<PabTradeRecord>() {});
            if (pabTrade == null) throw new BusinessException("交易返回异常");
            tradeRecord.setBankFlowNo(pabTrade.getBankFlowNo());
            updateTradeRecordStatus(tradeRecord, pabTrade.getPabTradeStatus());
        } else {
            List<Map<String,Object>> listMap = new ArrayList<>();
            for (TradeRecord tradeRecord : tradeRecordList) {
                Map<String, Object> nmap = new HashMap<>();
                tradeRecord.setInitiateTime(new Date());
                putTradeRecordMapParam(nmap, tradeRecord);
                listMap.add(nmap);
            }
            Map<String,Object> jsonMap = MapUtil.generate(map1 -> map1.put("tradeRecordListJson", JsonUtil.objectToJson(listMap)));
            String reqUrl = platProduct.getNetworkFreightUrl() + "/platform/psb/paymentTransferBatch";
            String batchTradeNo = PlatRequest.request(loginUser.getToken(), reqUrl, jsonMap, new TypeToken<String>() {});
            for (TradeRecord tradeRecord : tradeRecordList) {
                tradeRecord.setBatchTradeNo(batchTradeNo);
                updateTradeRecordStatus(tradeRecord, PabTradeRecord.PabTradeStatus.handle);
            }
        }
        tradeRecordService.updateBatchById(tradeRecordList);
    }
    /// 赋值参数
    private void putTradeRecordMapParam(Map<String, Object> map, TradeRecord tradeRecord) {
        BankCard paymentBackCard = tradeRecord.getPaymentBackCard();
        BankCard collectionBackCard = tradeRecord.getCollectionBackCard();
        tradeRecord.setBankType(TradeRecord.BankType.pabBankPay);
        tradeRecord.setPaymentCapitalAccount(paymentBackCard.getBankAccNo());
        tradeRecord.setIncomeCapitalAccount(collectionBackCard.getBankAccNo());
        map.put("tranAmount", tradeRecord.getMoney());
        map.put("outAcctNo", paymentBackCard.getBankAccNo());
        map.put("outAcctName", paymentBackCard.getHoldCardName());
        map.put("outBankShortName", paymentBackCard.getBankShortName());
        map.put("inAcctBankNode", collectionBackCard.getBankCode());
        map.put("inAcctRecCode", collectionBackCard.getBankCode());
        map.put("inAcctBankName", collectionBackCard.getBankShortName());
        map.put("inAcctProvinceCode", collectionBackCard.getCityCode());
        map.put("inAcctCityName", collectionBackCard.getOpenAddress());
        map.put("inBankShortName", collectionBackCard.getBankShortName());
        map.put("inAcctNo", collectionBackCard.getBankAccNo());
        map.put("inAcctName", collectionBackCard.getHoldCardName());
        map.put("tradeNo", tradeRecord.getTradeNo());
        map.put("remark", tradeRecord.getRemark());
        map.put("unionFlag", !Objects.equals(paymentBackCard.getBankCode(), collectionBackCard.getBankCode()));
        map.put("usage", tradeRecord.getTradeType().name);
        map.put("personFlag", collectionBackCard.getBankAccType()== BankCard.BankAccType.businessAcc?"owned":"personal");


    }
    /// 更新状态
    private void updateTradeRecordStatus(TradeRecord tradeRecord, PabTradeRecord.PabTradeStatus status) {
        if (PabTradeRecord.PabTradeStatus.success == status) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
            tradeRecord.setFinishTime(new Date());
        } else if (PabTradeRecord.PabTradeStatus.fail == status) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
            tradeRecord.setFinishTime(new Date());
        } else {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        }
    }
}
